<template>
  <div>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item prop="subjectId" label="所属栏目">
            <el-cascader
              @change="selectParentChange"
              :options="subjectTreeData"
              clearable
              :props="{ expandTrigger: 'hover', value: 'id',label: 'name',children: 'children' }"
              v-model="pKeys"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="subjectId" label="课程类型">
            <el-select v-model="form.courseType" placeholder="请选择课程类型">
              <el-option label="新手入门" :value="0" />
              <el-option label="免费好课" :value="1" />
              <el-option label="技能提高" :value="2" />
              <el-option label="实战开发" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="subjectId" label="课程难度">
            <el-select v-model="form.difficulty" placeholder="课程难度">
              <el-option label="入门" :value="0" />
              <el-option label="初级" :value="1" />
              <el-option label="中级" :value="2" />
              <el-option label="高级" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="title" label="长标题">
            <el-input v-model="form.title" placeholder="长标题" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="shortTitle" label="短标题">
            <el-input v-model="form.shortTitle" placeholder="短标题" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="price" label="价格">
            <el-input-number
              v-model="form.price"
              :min="1"
              :max="1000"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="lessonNum" label="课时">
            <el-input-number
              v-model="form.lessonNum"
              :min="1"
              :max="1000"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="courseDesc" label="课程描述">
            <el-input
              v-model="form.courseDesc"
              type="textarea"
              :rows="2"
              placeholder="请输入描述"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialong__button--wrap">
      <el-button @click="close">取消</el-button>
      <el-button :loading="subLoading" type="primary" @click="setListData">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, unref, PropType } from 'vue'
import Editor from '_c/Editor/index.vue'
import { Message } from '_c/Message'
import { formatTime } from '@/utils'
import { InfoWriteParams, InfoWriteRules } from './types'
import { getDetApi, setApi, getParentCategoryListApi } from '../api'

const requiredRule = {
  required: true,
  message: '该项为必填项'
}

export default defineComponent({
  name: 'IfnoWrite',
  components: {
    Editor
  },
  props: {
    info: {
      type: Object as PropType<any>,
      default: () => null
    }
  },
  emits: ['close', 'success'],
  setup(props, { emit }) {
    const formRef = ref<HTMLElement | null>(null)
    const editorRef = ref<HTMLElement | null>(null)
    const subLoading = ref<boolean>(false)
    const subjectTreeData = ref<object[]>([])
    // 父节点数组
    const pKeys = ref<number[]>([]);
    const form = reactive<InfoWriteParams>({
      id: '', // id
      subjectId: 0, // 课程所示栏目
      subjectParentId: 0, // 一级栏目
      title: '', // 长标题
      shortTitle: '', // 短标题
      price: 0, // 价格
      lessonNum: 0, // 课时
      courseDesc: '', // 课程描述
      courseType: 0, // 课程类型
      difficulty: 0, // 课程难度
      remarks: '' // 课程详情
    })

    const rules = reactive<InfoWriteRules>({
      subjectId: [requiredRule],
      shortTitle: [requiredRule],
      price: [requiredRule],
      remarks: [requiredRule],
      courseDesc: [requiredRule],
      title: [requiredRule]
    })

    async function getDet() {
      if (props.info) {
        const id = (props.info as any).id
        try {
          const res = await getDetApi({
            params: {
              id: id
            }
          })
          if (res) {
            for (const key in form) {
              if (key === 'importance') {
                form[key] = res.data[key].toString()
              } else {
                form[key] = res.data[key]
              }
            }
            pKeys.value = [res.data['subjectParentId'], res.data['subjectId']]
          }
        } catch (e) {
          console.log(e)
        }
      }
    }
    getDet()

    // 获取树形课程栏目
    const getParentCategoryList = async() => {
      const res = await getParentCategoryListApi()
      console.info('获取课程分类树形数据：', res)
      if (res.data.length > 0) {
        subjectTreeData.value = res.data
      } else {
        subjectTreeData.value = []
      }
    }
    getParentCategoryList()

    // 父级分类中改变
    const selectParentChange = () => {
      const len = pKeys.value.length
      if (len > 0) {
        form.subjectParentId = pKeys.value[0]
        form.subjectId = pKeys.value[len - 1]
      } else {
        form.subjectId = 0
        form.subjectParentId = 0
      }
    }

    // 新增或者编辑
    function setListData() {
      const formRefWrap = unref(formRef as any)
      const editorRefWrap = unref(editorRef as any)
      try {
        subLoading.value = true
        formRefWrap.validate(async(valid: boolean) => {
          if (valid) {
            const formData = unref(form)
            const res = await setApi({
              data: formData
            })
            if (res) {
              Message.success(form.id ? '编辑成功' : '新增成功')
              emit('success', form.id ? 'edit' : 'add')
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } catch (err) {
        console.log(err)
      } finally {
        subLoading.value = false
      }
    }

    function close() {
      emit('close')
    }

    return {
      formRef, editorRef,
      subLoading,
      form,
      rules,
      setListData,
      close,
      getDet,
      subjectTreeData,
      selectParentChange,
      pKeys
    }
  }
})
</script>

<style>
</style>
